package com.leyou.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.leyou.common.exceptions.LyException;
import com.leyou.common.utils.RegexUtils;
import com.leyou.user.entity.User;
import com.leyou.user.dto.UserDTO;
import com.leyou.user.mapper.UserMapper;
import com.leyou.user.service.UserService;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import static com.leyou.common.constants.MQConstants.ExchangeConstants.SMS_EXCHANGE_NAME;
import static com.leyou.common.constants.MQConstants.RoutingKeyConstants.VERIFY_CODE_KEY;


@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private BCryptPasswordEncoder passwordEncoder;

    private static final String KEY_PREFIX = "user:verify:phone:";

    //校验手机号或用户名是否存在
    @Override
    public Boolean isDataExists(String data, Integer type) {

        if (type!=1 && type!=2){
            throw new LyException(400,"请求参数有误");
        }
        //查询记录
        Integer count = this.query()
                .eq(type == 1, "username", data)//1是用户名
                .eq(type == 2, "phone", data)//2是手机
                .count();
        return count==1;
    }

    //生产者  发送短信验证码
    @Override
    public void sendVerifyCode(String phone) {
        //1.校验手机号格式
        if (!RegexUtils.isPhone(phone)){
            throw new LyException(400,"手机号格式有误！");
        }
        //2.生成验证码
        String code = RandomStringUtils.randomNumeric(6);
        System.out.println("================= code ==================== " + code);
        //3.调用amqp,发送短信
        Map<String,String> msg = new HashMap<>();
        msg.put("phone",phone);
        msg.put("code",code);
        amqpTemplate.convertAndSend(SMS_EXCHANGE_NAME,VERIFY_CODE_KEY,msg);//交换机  路由key  消息
        //4.短信验证码存入redis
        redisTemplate.opsForValue().set(KEY_PREFIX+phone,code,5, TimeUnit.MINUTES);
    }

    //注册用户
    @Override
    public void register(User user, String code) {
        //1.校验用户验证码
        //取出redis中的真实验证码
        String cacheCode = redisTemplate.opsForValue().get(KEY_PREFIX + user.getPhone());
        if (!StringUtils.equals(cacheCode,code)){
            throw new LyException(400,"验证码错误！");
        }
        //2.校验用户数据

        //3.对密码加密
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        //4.写入数据库
        this.save(user);
    }

    //根据用户名和密码查询用户
    @Override
    public UserDTO queryUserByNameAndPassword(String username, String password) {
        //1.先根据用户名查询
        User user = this.query().eq("username", username).one();
        //2.判断结果
        if (user==null){
            throw new LyException(400,"用户名或密码错误！");
        }
        //3.校验密码
        //查询时要对密码进行加密后判断是否一致
        boolean matches = passwordEncoder.matches(password, user.getPassword());
        if (!matches){
            throw new LyException(400,"用户名或密码错误！");
        }
        UserDTO userDTO = new UserDTO(user);
        return userDTO;
    }
}